package com.summli.basic.class07;

import java.util.Stack;

/**
 * 非递归方式实现二叉树的先序、中序、后序遍历
 *
 * 1）任何递归函数都可以改成非递归
 *
 * 2）自己设计压栈的来实现
 */
public class Code02_UnRecursiveTraversalBT {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int v) {
            value = v;
        }
    }

    // 前序遍历
    public static void pre(Node head) {
        if(head == null){
            return;
        }
        Stack<Node> stack = new Stack<Node>();
        stack.push(head);
        while(!stack.isEmpty()){
            Node pop = stack.pop();
            System.out.println(pop.value);
            if(pop.right != null){
                stack.push(pop.right);
            }
            if(pop.left != null){
                stack.push(pop.left);
            }
        }
    }

    // 中序遍历
    public static void in(Node head) {
        Stack<Node> stack = new Stack<Node>();
        while(!stack.isEmpty() || head != null){
            if(head != null){//只要左侧有值就进行压入
                stack.push(head);
                head = head.left;
            }else{//弹出中间端点，打印，并找到右点，重复操作
                Node pop = stack.pop();
                System.out.println(pop.value);
                head = pop.right;
            }
        }
    }

    // 后序遍历
    public static void pos1(Node head) {
        if(head == null){
            return;
        }
        Stack<Node> stack = new Stack<>();
        Node cur = null;
        Node help = head;
        stack.push(head);
        while(!stack.isEmpty()){
            cur = stack.peek();
            if(cur.left != null && cur.left != help && cur.right != help){
                stack.push(cur.left);
            }else if(cur.right != null && cur.right != help){
                stack.push(cur.right);
            }else{
                System.out.println(stack.pop().value);
                help = cur;
            }
        }
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);

        pre(head);
        System.out.println("========");
        in(head);
        System.out.println("========");
        pos1(head);
        System.out.println("========");
    }
}
